/**
 * Created by weng on 2018/4/5.
 */
/**
 * Created by zhuangy on 2018/3/9.
 */
var sea = require('../common/sea');
var sqlOrm = require('../common/sqlModel');
let question = require("./question")
let  accountsList = {}

class Question {
  // http://127.0.0.1:8083/wx/1001/bussInfo/xxxx/code
  async init(io) {
    try {
      io.on('connection', function (client) {

        console.log("connection")
        /// 进入房间，记录用户信息
        client.on('inRoom', async function (data,fn) {
          try {
            console.log("inRoom")
            let id = data.id
            let signDataString = sea.decrypt(sea.key, sea.vi, id);

            if (typeof signDataString === 'string') signDataString = JSON.parse(signDataString);
            if (signDataString.code != 200) {
              console.error("没有账号信息断开 并退出 err", signDataString)
              global.loggersFile.error("没有账号信息断开 并退出 err", signDataString)
              if(fn)
                fn({code:500,msg:"没有账号信息断开 并退出"})
              client.disconnect()
              return
            }
            const signDecodedInfo = JSON.parse(signDataString.decoded);
            let userId = signDecodedInfo.id;

            //let userId = data.id;
            //console.log("accountsList[userId]",accountsList[userId])
            if(accountsList[userId]){
              ///把原来的账号顶掉
              for(var k in  global.roomsAccount){
                for (var j in global.roomsAccount[k]['clients']){
                  for(var l in global.roomsAccount[k]['clients'][j]){
                    if(global.roomsAccount[k]['clients'][j][l].accountid == userId){
                      console.log("把原来的账号顶掉",accountsList[userId])
                      //console.log("把原来的账号顶掉",j)
                      //console.log("把原来的账号顶掉 len 1",global.roomsAccount[k]['clients'][j].length)
                      global.roomsAccount[k]['clients'][j].splice(l,1)
                      //console.log("把原来的账号顶掉 len 2",global.roomsAccount[k]['clients'][j].length)
                      //global.roomsAccount[k]['clients'][j][l].disconnect()

                      // console.log("global.roomsAccount[k]['clients'][j][l]",global.roomsAccount[k]['clients'][j][l])

                      // global.roomsAccount[k]['clients'][j][l].disconnect()

                    }
                  }
                }
              }
            }
            accountsList[userId] = userId;
            client.accountid = userId; // data.id //
            let accountInfo
            accountInfo = await sqlOrm.app_account.findAsync({id: userId});
            /// 没有账号信息断开 并退出
            if (accountInfo <= 0) {
              console.error("没有账号信息断开 并退出 err", accountInfo)
              global.loggersFile.error("没有账号信息断开 并退出 err", accountInfo)
              if(fn)
                fn({code:500,msg:"没有账号信息断开 并退出"})
              client.disconnect()

              return
            }

            client.accountInfo = accountInfo[0];
            let roomType = data.roomType;

            console.log("roomType",roomType)

            let roomInfo = global.roomsAccount[roomType];
            if (!roomInfo.clients[roomInfo.roomNum]) roomInfo.clients[roomInfo.roomNum] = [];

            console.log("roomInfo.roomNum",roomInfo.roomNum)

            roomInfo.clients[roomInfo.roomNum].push(client)
            client.roomId = roomInfo.roomNum;
            client.roomType = roomType;
            client.score = 0;
            client.answered = 1;

            let ClientsInfo = roomInfo.clients[roomInfo.roomNum]

            //console.log("ClientsInfo",ClientsInfo.length)

            //client.write({code:201})
            // client.end("sucess-end")

            for (var clinetInfo  of ClientsInfo) {
              /// 通知客户端人数变化
              console.log("通知客户端人数变化",clinetInfo.accountid)
              console.log(" 通知客户端人数变化 client.roomId",client.roomId)

              clinetInfo.emit("numChange", {count:ClientsInfo.length,maxCount:roomType })
            }
            if(fn)
              fn({code:200,count:ClientsInfo.length,msg:"success"})

            /// 通知客户端开始答题
            if (ClientsInfo.length == roomType - roomInfo['rate'][roomInfo.roomNum]) {
              for (var clinetInfo  of ClientsInfo) {
                /// 通知客户端开始答题
                console.error("startQuestion clinetInfo.accountid ",clinetInfo.accountid)
                console.error("client.roomId",client.roomId)

                clinetInfo.emit("startQuestion",{count:roomType,time:new Date().getTime(),startTime:3})

                /// 扣金币
                let roomTable = await sqlOrm.roomInfo.findAsync({type:roomType})
                let golden = roomTable[0].golden
                clinetInfo.accountInfo.golden -= golden
                clinetInfo.accountInfo.saveAsync()
              }
              await  question.startQuestion(roomInfo, roomInfo.roomNum)
              roomInfo.roomNum += 1;
              console.log("roomType:",roomType)
              let rewardInfo = await sqlOrm.reward.findAsync({type:roomType})
              console.log("rewardInfo:",rewardInfo)
              let rate = Math.floor(Math.random()* rewardInfo[0].rate)

              roomInfo['rate'][roomInfo.roomNum] = rate;
              console.log("rate is:",roomInfo['rate'])
              roomInfo.clients[roomInfo.roomNum] = [];
            }

          } catch (e) {
            console.error("报错没有账号信息断开 并退出 e", e)
            global.loggersFile.error("inRoom err", e)
            client.disconnect()
          }
        })
        /// 开始答题
        client.on('answer', function (data,fn) {
          try {
            let questions = global.roomsAccount[client.roomType]['questions'][client.roomId]
            let questionId = data.questionId;
            let answer = data.answer;
            if (questionId == questions.id && answer == questions.answer && client.answered != 1) {
              /// 分数+1
              let score = 10 - (new Date().getTime() - questions.time) / 1000
              client.score += (score > 0 ? score : 0);
              client.answered = 1
              if(fn)
                fn({code:200,msg:"success"})
            }else{
              if(fn)
                console.error("================================")
              console.error("accountid",client.accountid)
              console.error("questionId",questionId)
              console.error("questions.id",questions.id)
              console.error("answer",answer)
              console.error("questions.answer",questions.answer)
              console.error("================================")

              fn({code:500,msg:"answer wrong"})
              client.answerWrong = 1
              //client.disconnect()
            }
          } catch (e) {
            global.loggersFile.error("answer err", e)
          }
        });

        client.on('disconnect', function () {
          // console.error("disconnect")
          ///  离线
          try {
            client.answerStaus = -1
            console.error("disconnect ",client.accountid)

            // console.error("global.roomsAccount[client.roomType]",!!global.roomsAccount[client.roomType])
            setTimeout(function(){
              if (!global.roomsAccount
                ||!global.roomsAccount[client.roomType]
                || !global.roomsAccount[client.roomType]["clients"]
                || !global.roomsAccount[client.roomType]["clients"][client.roomId])	{
                return
              }

              let clients = global.roomsAccount[client.roomType]["clients"][client.roomId];
              console.error("clients.1111",clients.length)
              for (let i in clients) {
                if (clients[i].accountid == client.accountid) {
                  console.error("client.accountid",client.accountid)
                  clients.splice(i, 1);
                }
              }
              console.error("clients.22222",clients.length)

            },10)

          } catch (e) {
            console.error("disconnect","error")
            global.loggersFile.error("disconnect err", e)
          }
        });

        client.on('error', function () {

        });
      });
    } catch (err) {
      console.error("err", err);
      cb({code: 50001, info: {}, msg: err});
    }
  }

}

module.exports = new Question();